<?php
namespace Auth\Controller;
use Think\Controller;
class WechatController extends Controller {
	public function __construct(){
		
	}
    // 接入微信
	public function index(){
		//获得参数 signature nonce token timestamp echostr
		$nonce     = $_GET['nonce'];
		$token     = C(wx_token);
		$timestamp = $_GET['timestamp'];
		$echostr   = $_GET['echostr'];
		$signature = $_GET['signature'];
		//形成数组，然后按字典序排序
		$array = array();
		$array = array($nonce, $timestamp, $token);
		sort($array);
		//拼接成字符串,sha1加密 ，然后与signature进行校验
		$str = sha1( implode( $array ) );
		if( $str  == $signature && $echostr ){
			//第一次接入
			echo  $echostr;
			exit;
		}else{
			//转向发送欢迎语句
			$this->reponseMsg();
		}
	}
	//关注及消息的事件响应
	public function reponseMsg(){
		$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
		$postObj = simplexml_load_string( $postArr );
		//event事件判断
		if( strtolower( $postObj->MsgType) == 'event'){
			//如果是关注 subscribe 事件
			$access_token = get_wx_access_token();
			if( strtolower($postObj->Event == 'subscribe') ){
				//回复用户消息(纯文本格式)	
				$toUser   = $postObj->FromUserName;
				$fromUser = $postObj->ToUserName;
				$time     = time();
				$msgType  =  'text';
				$content  = '欢迎关注 我公众号！';
				$template = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
				$info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
				echo $info;				
				//注册会员
				//查找数据表中带有这条openid的用户信息	
				$wxuser = M('Wxuser');
				$user = M('User');
			    //向微信请求该用户信息并处理
				$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$toUser."&lang=zh_CN";
				$res = http_curl($url);
				$map['openid'] = $res['openid'];
				$only = $wxuser->Where($map)->find();
			 //如果没有这条信息则将信息存入微信用户表
			 if(!$only){
				$wxres = array(
                'openid' => $res['openid'],
                'nickname' => $res['nickname'],
                'sex' => $res['sex'],
                'city' => $res['city'],
                'headporurl' => $res['headimgurl'],
                'followstate' =>$res['subscribe'],
                'subscribe_time' =>$res['subscribe_time'],
                'regtime' => time(),
				);
				if($wxuser->create($wxres)) {
				//创建成功发布存入数据库
					$result = $wxuser->add($wxres);
				}else{
					$this->error($wxuser->getError());
				}
				//存入便签用户表
				$userinfo = array(
					'openid' => $res['openid'],
					'nickname' => $res['nickname'],
					'sex' => $res['sex'],
					'city' => $res['city'],
					'followstate' =>$res['subscribe'],
					'headporurl' => $res['headimgurl'],
					'scores' => '0',
					'vip' => '1',
					'point' => '0',
					'sid' => '0',
					'from' => 'wechat',
					'disabled' => '1',
					'regtime' => time(),
				);
				if($user->create($userinfo)) {
					//创建成功发布存入数据库
					$result = $user->add($userinfo);
				}else{
					$this->error($user->getError());
				}  
			 }else{
				 //已是会员则更新微信昵称和头像
				$data['nickname'] = $res['nickname'];
				$data['headporurl'] = $res['headimgurl'];
				$data['followstate'] = $res['subscribe'];
				$only = $wxuser->where($map)->save($data);
				$only = $user->where($map)->save($data);
			 }
			}
			//取关事件
			if( strtolower($postObj->Event == 'unsubscribe') ){
				$fromUser= $postObj->FromUserName;
				$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$fromUser."&lang=zh_CN";
				$res = http_curl($url);
				$map['openid'] = $res['openid'];
				$data['followstate'] = 0;
				$wxuser = M('Wxuser');
				$user = M('User');
				$wxuser->where($map)->save($data);
				$user->where($map)->save($data);					
			}
		}
		//消息回复事件
		if( strtolower( $postObj->MsgType) == 'text'){
			$toUser   = $postObj->FromUserName;
			$fromUser = $postObj->ToUserName;
			$time     = time();
			$msgType  = 'text';
			$template = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[%s]]></MsgType>
				<Content><![CDATA[%s]]></Content>
				</xml>";
			$fromMesg = $postObj->Content;
			$where['frommesg'] = array('like','%'.$fromMesg.'%');
			$only = M("Wxmesg")->where($where)->find();
			$tomesg = $only['tomesg'];
			$content = $tomesg;
			$info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
			echo $info;	
		}
	}
	//微信自定义菜单
	public function createMenu(){
    	//定义文件编码
		header('content-type:text/html;charset=utf-8');
    	//获取token
    	$access_token = get_wx_access_token();
   		//请求地址	
    	$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
    	//菜单列表
        $postArr = array(
            'button'=>array(
                array(
                    'name'=>urlencode('帮助'),
                    'type'=>'view',
					'url'=>'http://www.icchen.com'
                ),
                array(
                    'name'=>urlencode('服务'),
                    'type'=>'view',
					'url'=>'http://www.icchen.com'
                ),
                array(
                    'name'=>urlencode('我的'),
                    'sub_button'=>array(
                    	array(
                            'name'=>urlencode('我的'),
                            'type'=>'view',
                            'url'=>'http://www.icchen.com'
                        ),                                                                  
						array(
                            'name'=>urlencode('信息'),
                            'type'=>'view',
                            'url'=>'http://www.icchen.com'
                        ),
                        
                    ),
                ),

        ));
        //菜单数组转json数据包
        $postJson = urldecode(json_encode($postArr));
        //通过向请求地址发送数据包完成自定义菜单
        $res = http_curl($url,'post','json',$postJson);
		echo $res;
		var_dump($res);
		var_dump($access_token);
	}
	 public function getuser(){
		 $access_token = get_wx_access_token();
		 $toUser = 'o99t20lopT4ZTYtN-IaKIs0V8RTo';
		 $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$toUser."&lang=zh_CN";
		 $res = http_curl($url);
		 var_dump($res);
	 }


		 
}